#define _CRT_SECURE_NO_WARNINGS 1

#include"ListNode.h"

void ListPrint(ListNode* head)
{
	assert(head);
	ListNode* cur = head->next;
	while (cur!=head)
	{
		printf("%d ", cur->val);
		cur = cur->next;
	}
	printf("\n");
}
void ListPushBack(ListNode* head, DataType x)
{
	assert(head);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc failed");
		return;
	}
	ListNode* tail = head->prev;
	newnode->val = x;
	newnode->next = head;
	newnode->prev = tail;
	tail->next = newnode;
	head->prev = newnode;
}
ListNode* ListInit()
{
	ListNode* head=(ListNode*)malloc(sizeof(ListNode));
	if (head == NULL)
	{
		perror("malloc failed");
		return NULL;
	}
	head->next = head;
	head->prev = head;
	return head;
}
void ListPushFront(ListNode* head, DataType x)
{
	assert(head);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc failed");
		return;
	}
	newnode->val = x;
	newnode->next = head->next;
	newnode->prev = head;
	head->next = newnode;
	newnode->next->prev = newnode;
}
ListNode* ListFind(ListNode* head, DataType x)
{
	assert(head);
	ListNode* cur = head->next;
	while (cur != head)
	{
		if (cur->val == x)
		{
			return cur;
		}
		cur = cur->next;
	}
}
void ListPopFront(ListNode* head)
{
	assert(head);
	ListNode* tmp = head->next;
	head->next = tmp->next;
	tmp->next->prev = head;
	free(tmp);
}
void ListPopBack(ListNode* head)
{
	ListNode* tmp = head->prev;
	head->prev = tmp->prev;
	tmp->prev->next = head;
	free(tmp);
}
void ListInsert(ListNode*pos, DataType x)
{
	assert(pos);
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc failed");
		return;
	}
	newnode->val = x;
	newnode->prev = pos;
	newnode->next = pos->next;
	pos->next = newnode;
	newnode->next->prev = newnode;
}
void ListDestroy(ListNode* head)
{
	assert(head);
	ListNode* cur = head->next;
	while(cur!=head)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(head);
}
void ListPop(ListNode* head, DataType x)
{
	assert(head);
	ListNode* cur = head->next;
	while (cur != head)
	{
		if (cur->val == x)
		{
			cur->next->prev = cur->prev;
			cur->prev->next = cur->next;
			free(cur);
			return;
		}
		cur = cur->next;
	}
}






